package com.zly.app.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zly.app.dao.AppInfoDao;
import com.zly.app.dao.AppVersionDao;
import com.zly.app.dto.AppInfoDto;
import com.zly.app.entity.AppInfo;
import com.zly.app.entity.AppVersion;
import com.zly.app.util.SysConStatus;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.Filter;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;

@Service
public class AppInfoService {

    @Autowired
    AppInfoDao appInfoDao;

    @Autowired
    AppVersionDao appVersionDao;

    public PageInfo<AppInfo> getPage(AppInfoDto appInfoDto, Integer pageNum) {
        PageHelper.startPage(pageNum, SysConStatus.pageSize,"id desc");
        AppInfo appInfo = new AppInfo();
        BeanUtils.copyProperties(appInfoDto,appInfo);
        List<AppInfo> list = appInfoDao.queryAll(appInfo);
        return  new PageInfo<>(list);
    }

    public boolean vailApk(Long appid, String apkname) {
        if (appid==null||appid==0){
            return appInfoDao.vailApkbyName(apkname) <= 0;
        }else {
            if (appInfoDao.vailApk(appid,apkname)==1) {
                return true;
            }else if(appInfoDao.vailApk(appid, apkname) == 0){
                return appInfoDao.vailApkbyName(apkname) <= 0;
            }
        }
        return false;
    }

    public void saveAndUp(AppInfo appinfo) {
        if (appinfo.getId()==0){
            appInfoDao.insert(appinfo);
        }else {
            appInfoDao.update(appinfo);
        }
    }

    public AppInfo selApp(Long appid) {
        return appInfoDao.queryById(appid);
    }

    public void delApp(Long appid,String realPath) {
        //删除apk文件
        AppVersion appVersion = new AppVersion();
        List<AppVersion> list = appVersionDao.queryAll(appVersion);
        for (AppVersion version : list) {
            if (version.getDownloadlink()!=null){
                new File(realPath,version.getDownloadlink()).delete();
            }
        }
        //删除所有版本
        appVersionDao.deleteById(appid);
        //删除logo文件
        AppInfo appInfo = appInfoDao.queryById(appid);
        if (appInfo.getLogopicpath()!=null){
            new File(realPath,appInfo.getLogopicpath()).delete();
        }

        //删除app
        appInfoDao.deleteById(appid);


    }

    public void upStatus(Long id, Long status) {
        appInfoDao.upStatus(id,status);
    }
}
